<template>
  <div class="row" v-if="!succeeded">
    <div class="col-12 text-subtitle1 text-center">忘记密码</div>
    <div class="col-12 text-subtitle2 text-center">通过Email重置密码</div>
    <q-banner inline-actions rounded class="col-12 text-white bg-negative q-mt-sm" v-if="serverErrorMessage">
      {{serverErrorMessage}}
      <template v-slot:action>
        <q-btn flat icon="close" size="sm" dense @click="serverErrorMessage=null" />
      </template>
    </q-banner>
    <q-input class="col-12 q-mt-md" v-model="form.username" placeholder="用户名" outlined square dense autofocus
      :error="v$.username.$error" :error-message="e$(v$.username.$errors)" no-error-icon :hide-bottom-space="true"
      :disable="workingState">
      <template v-slot:append>
        <q-icon name="person" />
      </template>
    </q-input>
    <q-input class="col-12 q-mt-md" v-model="form.email" placeholder="电子邮箱" outlined square dense
      :error="v$.email.$error" :error-message="e$(v$.email.$errors)" no-error-icon :hide-bottom-space="true"
      :disable="workingState">
      <template v-slot:append>
        <q-icon name="email" />
      </template>
    </q-input>
    <q-btn class="q-mt-md col-12" color="primary" label="确定" :loading="workingState" @click="confirm">
      <template v-slot:loading>
        <q-spinner class="on-left" />
        提交中...
      </template>
    </q-btn>
    <q-btn class="q-mt-sm col-12" color="primary" outline label="返回登录" :disable="workingState" to="/comm/auth/login" />
  </div>
  <div class="row" v-else>
    <q-banner inline-actions rounded class="col-12 text-white bg-positive q-mt-sm">
      找回密码邮件发送成功
      <template v-slot:action>
        <q-btn flat color="white" label="转至首页" to="/" />
      </template>
    </q-banner>
  </div>
</template>

<script lang="ts">
export default {
  name: 'forgotPasswordStd'
}
</script>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import useVuelidate from '@vuelidate/core'

const serverErrorMessage = ref('')
const workingState = ref(false)
const e$ = $f.getFieldErrStr

const succeeded = ref(false) // 表示忘记密码的请求发送成功

const form = reactive({
  username: '',
  email: ''
})

//表单验证
const rules = {
  username: {
    required: $f.validators.required,
    username: $f.validators.username
  },
  email: {
    required: $f.validators.required,
    email: $f.validators.email
  }
}

const v$ = useVuelidate(rules, form, { $autoDirty: true })

const confirm = function () {
  void v$.value
    .$validate()
    .then((valRes) => {
      if (valRes) {
        workingState.value = true
        serverErrorMessage.value = ''
        $f.axios
          .post('comm/auth/forgot-password', form)
          .then(() => {
            workingState.value = false
            succeeded.value = true
          })
          .catch((err) => {
            serverErrorMessage.value = $f.getAxiosErrMsg(err)
            workingState.value = false
          })
      }
    })
}
</script>
